package summer.graph;

import java.util.Arrays;
import java.util.LinkedList;

public class Solution542 {
    public static void main(String[] args) {
        int[][] mat = new int[][]{{0, 0, 0}, {0, 1, 0}, {1, 1, 1}};
        updateMatrix(mat);
    }

    public static int[][] updateMatrix(int[][] mat) {
        int m = mat.length;
        int n = mat[0].length;
        int[] dx = new int[]{1, -1, 0, 0};
        int[] dy = new int[]{0, 0, -1, 1};
        LinkedList<int[]> queue = new LinkedList<>();
        int[][] res = new int[m][n];
        boolean[][] used = new boolean[m][n];
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (mat[i][j] == 0) {
                    queue.add(new int[]{i, j});
                    used[i][j] = true;
                }
            }
        }
        int dis = 0;
        while (!queue.isEmpty()) {
            int size = queue.size();
            dis++;
            while (size-- > 0) {
                int[] curs = queue.removeFirst();
                for (int i = 0; i < 4; i++) {
                    int x = curs[0] + dx[i];
                    int y = curs[1] + dy[i];
                    if (x >= 0 && x < m && y >= 0 && y < n && !used[x][y]) {
                        res[x][y] = dis;
                        used[x][y] = true;
                        queue.add(new int[]{x, y});
                    }
                }
            }
        }
        return res;
    }
}
